import { defineStore } from 'pinia';
import { getUserIdentity, isPilot, isOrganization, getPilotProfile, getOrganizationInfo } from '@/api/user';

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户基本信息
    userId: null as number | null,
    phone: '',
    token: '',
    
    // 用户身份信息
    userIdentity: null as any,
    isPilot: false,
    isOrganization: false,
    userType: 'none', // none, pilot, organization, both
    
    // 飞手信息
    pilotProfile: null as any,
    pilotStatus: '',
    canAcceptTask: false,
    
    // 组织方信息
    organizationInfo: null as any,
    orgStatus: '',
    canPublishTask: false,
    
    // 加载状态
    identityLoaded: false,
  }),
  
  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    
    // 是否为飞手（已审核通过）
    isApprovedPilot: (state) => state.isPilot && state.pilotStatus === '1',
    
    // 是否为组织方（已审核通过）
    isApprovedOrganization: (state) => state.isOrganization && state.orgStatus === '1',
    
    // 是否可以接单
    canAcceptTasks: (state) => state.canAcceptTask,
    
    // 是否可以发布任务
    canPublishTasks: (state) => state.canPublishTask,
    
    // 用户类型描述
    userTypeText: (state) => {
      switch (state.userType) {
        case 'pilot': return '飞手';
        case 'organization': return '组织方';
        case 'both': return '飞手+组织方';
        default: return '未注册';
      }
    }
  },
  
  actions: {
    // 设置登录信息
    setLoginInfo(userInfo: any) {
      this.userId = userInfo.userId;
      this.phone = userInfo.phone;
      this.token = userInfo.token;
      
      // 保存token到本地存储
      if (this.token) {
        uni.setStorageSync('drone_token', this.token);
      }
    },
    
    // 清除登录信息
    clearLoginInfo() {
      this.userId = null;
      this.phone = '';
      this.token = '';
      this.userIdentity = null;
      this.isPilot = false;
      this.isOrganization = false;
      this.userType = 'none';
      this.pilotProfile = null;
      this.pilotStatus = '';
      this.canAcceptTask = false;
      this.organizationInfo = null;
      this.orgStatus = '';
      this.canPublishTask = false;
      this.identityLoaded = false;
      
      // 清除本地存储
      uni.removeStorageSync('drone_token');
    },
    
    // 获取用户身份信息
    async fetchUserIdentity() {
      try {
        console.log('开始获取用户身份信息...');
        const response = await getUserIdentity();
        
        if (response.data.code === 200) {
          const identity = response.data.data;
          this.userIdentity = identity;
          this.isPilot = identity.isPilot || false;
          this.isOrganization = identity.isOrganization || false;
          this.userType = identity.userType || 'none';
          
          // 设置飞手信息
          if (identity.isPilot) {
            this.pilotProfile = identity.pilotProfile;
            this.pilotStatus = identity.pilotStatus || '';
            this.canAcceptTask = identity.pilotStatus === '1';
          }
          
          // 设置组织方信息
          if (identity.isOrganization) {
            this.organizationInfo = identity.organization;
            this.orgStatus = identity.orgStatus || '';
            this.canPublishTask = identity.orgStatus === '1';
          }
          
          this.identityLoaded = true;
          console.log('用户身份信息获取成功:', identity);
          console.log('Store状态更新后:');
          console.log('- isPilot:', this.isPilot);
          console.log('- isOrganization:', this.isOrganization);
          console.log('- pilotStatus:', this.pilotStatus);
          console.log('- orgStatus:', this.orgStatus);
          console.log('- canAcceptTask:', this.canAcceptTask);
          console.log('- canPublishTask:', this.canPublishTask);
          return identity;
        } else {
          console.error('获取用户身份信息失败:', response.data.msg);
          return null;
        }
      } catch (error) {
        console.error('获取用户身份信息异常:', error);
        return null;
      }
    },
    
    // 检查飞手身份
    async checkPilotStatus() {
      try {
        const response = await isPilot();
        if (response.code === 200) {
          const data = response.data;
          this.isPilot = data.isPilot || false;
          this.pilotStatus = data.status || '';
          this.canAcceptTask = data.canAcceptTask || false;
          return data;
        }
        return null;
      } catch (error) {
        console.error('检查飞手身份异常:', error);
        return null;
      }
    },
    
    // 检查组织方身份
    async checkOrganizationStatus() {
      try {
        const response = await isOrganization();
        if (response.code === 200) {
          const data = response.data;
          this.isOrganization = data.isOrganization || false;
          this.orgStatus = data.status || '';
          this.canPublishTask = data.canPublishTask || false;
          return data;
        }
        return null;
      } catch (error) {
        console.error('检查组织方身份异常:', error);
        return null;
      }
    },
    
    // 权限检查方法
    checkPermission(action: string): boolean {
      switch (action) {
        case 'accept_task':
          return this.canAcceptTasks;
        case 'publish_task':
          return this.canPublishTasks;
        case 'view_pilot_profile':
          return this.isPilot;
        case 'view_organization_info':
          return this.isOrganization;
        default:
          return false;
      }
    },
    
    // 显示权限提示
    showPermissionAlert(action: string) {
      let message = '';
      switch (action) {
        case 'accept_task':
          if (!this.isPilot) {
            message = '只有飞手才能接单，请先注册飞手信息';
          } else if (this.pilotStatus !== '1') {
            message = '飞手档案未通过审核，无法接单';
          }
          break;
        case 'publish_task':
          if (!this.isOrganization) {
            message = '只有组织方才能发布任务，请先注册组织信息';
          } else if (this.orgStatus !== '1') {
            message = '组织信息未通过审核，无法发布任务';
          }
          break;
        default:
          message = '权限不足';
      }
      
      if (message) {
        uni.showToast({
          title: message,
          icon: 'none',
          duration: 3000
        });
        return false;
      }
      return true;
    },
    
    // 初始化用户信息（登录后调用）
    async initUserInfo() {
      // 从本地存储获取token
      const token = uni.getStorageSync('drone_token');
      if (token) {
        this.token = token;
        
        // 获取用户身份信息
        await this.fetchUserIdentity();
      }
    }
  },
  
  persist: {
    key: 'user-store',
    storage: {
      getItem: (key: string) => uni.getStorageSync(key),
      setItem: (key: string, value: string) => uni.setStorageSync(key, value),
      removeItem: (key: string) => uni.removeStorageSync(key),
    },
    paths: ['token', 'userId', 'phone'] // 只持久化基本信息，身份信息每次都重新获取
  }
});
